package com.hujiang.basic.search.common.converter.req;

import com.alibaba.fastjson.JSONObject;
import com.hujiang.basic.search.common.converter.Converter;
import com.hujiang.basic.search.model.HJSearchRequest;
import com.hujiang.basic.search.model.HJSuggestRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.suggest.SuggestRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.Map;

/**
 * Created by zhanglibin on 2017/3/29.
 */
@Component
public class SuggestRequestConverter implements Converter<HJSuggestRequest, SuggestRequest> {
    @Override
    public SuggestRequest convert(HJSuggestRequest in) {
        SuggestRequest request = new SuggestRequest();
        request.indices(in.getIndex());
        SuggestBuilder suggestBuilder = buildSuggest(in.getSuggest());
        if(null != suggestBuilder){
            request.suggest(suggestBuilder);
        }
        return request;
    }


    private SuggestBuilder buildSuggest(JSONObject suggest){
        if(null != suggest && suggest.size()>0){
            String text = suggest.get("text").toString();
            SuggestBuilder builder = new SuggestBuilder();
            for (Map.Entry<String, Object> entry : suggest.entrySet()) {
               if(!"text".equals(entry.getKey())){
                   CompletionSuggestionBuilder suggestionsBuilder = new CompletionSuggestionBuilder(entry.getKey());
                   JSONObject completion = (JSONObject)(((JSONObject)(entry.getValue())).get("completion"));
                   suggestionsBuilder.text(text)
                           .field(completion.getString("field"))
                           .size(completion.getIntValue("size"));
                   builder.addSuggestion(suggestionsBuilder);
               }
            }
            return builder;
        }
        return null;
    }
}
